﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using cs499.Database;

namespace cs499.Admin
{
    public partial class ImportUser : System.Web.UI.Page
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (HttpContext.Current.Session["ImportUserLabelText"] != null && IsPostBack)
            {
                ImportUserLabel.Text = (string)HttpContext.Current.Session["ImportUserLabelText"];
                //OKButton.Enabled = false;
            }
            else if (IsPostBack)
            {
                ImportUserLabel.Text = "";
            }
            else
            {
                ImportUserLabel.Text = "";
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            LinkButton adminMenuButton = (LinkButton)Master.FindControl("LoginView").FindControl("AdminMenuButton");
            adminMenuButton.CssClass = "selected";

            if (ImportUserLabel.Text != "") return;
            if (HttpContext.Current.Session["CurrentDepartmentId"] != null)
            {
                int CurrentDepartmentId = (int)HttpContext.Current.Session["CurrentDepartmentId"];
                cs499.Database.Department CurrentDepartment = Database.ListOfDepartment.GetDepartment(ID: CurrentDepartmentId);
                ImportUserLabel.Text = "Input file containing information for new Users";
            }
            else
            {
                Response.Redirect("~/Admin/ListUsers.aspx");
            }
        }

        protected void CancelButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/ListUsers.aspx");
        }

        protected void ImportUserFileUpload_DataBinding(object sender, EventArgs e)
        {
            HttpContext.Current.Session["ImportUserLabelText"] = "Bad parse";
            Server.Transfer("~/Admin/ImportUser.aspx", true);
        }

        protected void OKButton_Click(object sender, EventArgs e)
        {
            if (!ImportUserFileUpload.HasFile)
            {
                String errmsg = "User must Specify File";
                if (ImportUserLabel.Text != errmsg)
                {
                    HttpContext.Current.Session["ImportUserLabelText"] = errmsg;
                    Server.Transfer("~/Admin/ImportUser.aspx", true);
                }
                return;
            }

            System.IO.StreamReader streamReader = new System.IO.StreamReader(ImportUserFileUpload.FileContent); 
            Model1Container db = new Model1Container();

            string line = null;
            int lineNumber = 0;
            List<string> usersThatAlreadyExist = new List<string>();
            List<string> usersAdded = new List<string>();
            System.Text.StringBuilder importStatus = new System.Text.StringBuilder();

            while ((line = streamReader.ReadLine()) != null)
            {
                lineNumber++;

                //only parse non-comment lines
                if (!line.StartsWith("#") && line != "" && line.Replace(",", "") != "")
                {
                    try
                    {
                        //make sure we have proper email format
                        if (!System.Text.RegularExpressions.Regex.IsMatch(line, @"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                        {
                            //error
                            if (!importStatus.ToString().Contains("Line #" + lineNumber))
                                importStatus.Append("Line #" + lineNumber + ": " + line + "<br />");
                            importStatus.Append("&emsp;&bull;The user name was not in correct email format<br />");
                            continue;
                        }

                        int currentDepartmentId = (int)HttpContext.Current.Session["CurrentDepartmentId"];
                        Department department = db.Set<Department>().FirstOrDefault(dep => (dep.Id == currentDepartmentId));

                        Faculty queriedFaculty = department.GetFaculty(Guid.Empty, emailaddress:line);
                        if (queriedFaculty == null)
                        {
                            //add new course to set that will go to database
                            department.CreateFaculty(Guid.Empty, line, isEmailCheckBox.Checked);

                            usersAdded.Add(line);
                        }
                        else
                        {
                            //keep track of what we're not adding
                            usersThatAlreadyExist.Add(line);
                        }
                    }
                    catch (Exception /*ex*/)
                    {
                        importStatus.Append("Line #" + lineNumber + ": " + line + "<br />");
                    }
                }
            }

            if (importStatus.Length != 0) //means we have reported errors
            {
                //insert the explanatory message before the errors
                importStatus.Insert(0, "There was an error processing the following line(s) in " + ImportUserFileUpload.FileName + "<br />");
                //add an extra space after the errors
                importStatus.Append("<br />");
                //tell the user what to do
                importStatus.Append("Please investigate and retry the import. No records were committed to the application.");

                ImportUserLabel.Text = importStatus.ToString();
                return;
            }
            else
            {
                //after all lines are successfully processed, then commit the changes to the database
                db.SaveChanges();

                //tell the user how many objects we imported
                importStatus.Append("Number of users imported: " + usersAdded.Count + "<br />");

                if (usersAdded.Count > 0)
                {
                    //tell the user which objects were imported
                    importStatus.Append("Users added: <ul>");
                    foreach (string slot in usersAdded)
                        importStatus.Append("<li>" + slot + "</li>");
                    importStatus.Append("</ul>");
                }
                
                //if we didn't import anything, tell the user
                if (usersThatAlreadyExist.Count > 0)
                {
                    importStatus.Append("<br />There were items that were not imported because they already existed in the application.<br />");
                    importStatus.Append("Number of users skipped: " + usersThatAlreadyExist.Count + "<br />");
                    //importStatus.Append("Time slots skipped: " + string.Join(", ", usersThatAlreadyExist.ToArray()));

                    importStatus.Append("Users skipped: <ul>");
                    foreach (string slot in usersThatAlreadyExist)
                        importStatus.Append("<li>" + slot + "</li>");
                    importStatus.Append("</ul>");
                }

                ImportUserLabel.Text = importStatus.ToString();
            }
        }
    }
}